<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NPopconfirm,
  NTag,
  NSwitch,
  NSelect,
  NImage,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import { router } from '@/router'
import default_image from '@/assets/images/mz.jpg'

defineOptions({ name: '优惠券发放' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '优惠券发放',
  initForm: {},
  doCreate: api.createCoupons,
  doUpdate: api.updateCoupons,
  doDelete: api.deleteCoupons,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({
  option_type: [],
  uploadAction: base_path + 'api/goods/brand/file',
  token: getToken(),
  onLevelData: []
})
//获取上级部门id
async function onleves(query) {
  let val = await api.getLeves({ key: query })
  data.onLevelData = val.data
}
//异步下拉获取上级
const loadingRef = ref(false)
const optionsRef = ref([])
const handleLeves = (query) => {
  if (!query.length) {
    optionsRef.value = []
    return
  }
  onleves(query)
  loadingRef.value = true
  // data.selectValue
  window.setTimeout(() => {
    data.onLevelData.value = data.onLevelData.filter((item) => ~item.label.indexOf(query))
    loadingRef.value = false
  }, 1e3)
}


onMounted(() => {
  api.getCouponsRuleList().then((res) => (data.option_type = res.data))
  api.getLever().then((res) => (data.levelData.value = res.data))
  $table.value?.handleSearch()
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 100,
    align: 'center',
    ellipsis: {tooltip: true},
  },

  {
    title: "姓名",
    key: 'user_name',
    width: 60,
    align: 'center',
    ellipsis: {tooltip: true},
    fixed: 'left',
  },
     {
    title: '优惠券类型',
    key: 'type_name',
    align: 'center',
    width:100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.type_name }
      )
    },
  },
      {
    title: '来源',
    key: 'come_name',
    align: 'center',
    width:100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.come_name }
      )
    },
  },
  {
    title: '面额',
    key: 'coupons_price',
    width: 60,
    align: 'center',
    ellipsis: {tooltip: true},
  },


  {
    title: '到期时间',
    key: 'expire_at',
    width: 140,
    align: 'center',
    ellipsis: {tooltip: true},
  },
    {
    title: '使用状态',
    key: 'is_used',
    align: 'center',
    width:100,
    ellipsis: { tooltip: true },
    render(row) {
      let ste = "未使用"
      if(row.is_used===1){
        ste = "已使用"
      }else if(row.is_used===2){
        ste = "已过期"
      }
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => ste }
      )
    },
  },
    {
    title: '订单号',
    key: 'order_id',
    align: 'center',
    width:100,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => row.order_id }
      )
    },
  },
    {
    title: '备注',
    key: 'remark',
    width: 140,
    align: 'center',
    ellipsis: {tooltip: true},
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    fixed: 'right',
    render(row) {

      return [
        withDirectives(
            h(
          NPopconfirm,
          {
            onPositiveClick: () => handleUpdateDisable(row),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'primary',
                    style: 'margin-right: 8px;',
                  },
                  {
                    default: () => '核销',
                    icon: renderIcon('material-symbols:activity-zone-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/category/delete']]
              ),
            default: () => h('div', {}, '确定设置核销吗?'),
          }
        ),
            [[vPermission, 'post/api/content/category/update']]
        ),
            h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ data_id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/category/delete']]
              ),
            default: () => h('div', {}, '确定删除该优惠券吗?'),
          }
        ),


      ]


    },
  },
]

async function handleUpdateDisable(row) {
  row.is_used = 1
  try {
    await api.updateCoupons(row)
    $message?.success(row.is_used ? '已核销' : '未核销')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.is_used === 1 ? 0 : 1
  }
}

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="优惠券发放">
    <template #action>
      <div>
        <NButton
          v-permission="'post/api/content/category/create'"
          class="float-right mr-15"
          type="primary"
          @click="handleAdd"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />优惠券发放
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getCoupons"
        :scroll-x="1200"
    >
      <template #queryBar>
        <QueryBarItem label="客户姓名" :label-width="80">
          <NInput
              v-model:value="queryItems.user_name"
              clearable
              type="text"
              placeholder="请输入客户姓名"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
        <QueryBarItem label="优惠券类型" :label-width="80">
              <NSelect
                v-model:value="queryItems.type"
                style="width: 150px"
                :options="data.option_type"
                clearable
                placeholder="请选类型"
              />
            </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading" @save="handleSave"
               style="width: 500px !important;"
    >
      <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80"
             :model="modalForm" :rules="validateAddUser">

        <NFormItem label="优惠券" path="type">
          <NSelect
            v-model:value="modalForm.coupons_id"
            :options="data.option_type"
            placeholder="请选择优惠券"
          />
        </NFormItem>

        <NFormItem label="指定用户" path="is_select_user">
              <n-space align="center">
                <NSwitch
                  v-model:value="modalForm.is_select_user"
                  :checked-value="1"
                  :unchecked-value="0"
                  :default-value="0"
                ><template #checked>指定用户</template><template #unchecked>全部用户</template>
                </NSwitch>
                <NSelect
                  multiple
                  v-if="modalForm.is_select_user === 1"
                  style="width: 260px"
                  v-model:value="modalForm.user_ids"
                  filterable
                  placeholder="输入用户姓名搜索"
                  :options="data.onLevelData"
                  :loading="loading"
                  clearable
                  remote
                  @search="handleLeves"
                />
              </n-space>
            </NFormItem>

        <NFormItem label="备注" path="remark">
          <NInput
            v-model:value="modalForm.remark"
            clearable
            placeholder="请输入备注"
          />
        </NFormItem>

      </NForm>
    </CrudModal>


  </CommonPage>
</template>
